package cn.nawang.ebeim.client.version;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class Serializer  {

    private Kryo kryo = new Kryo();

    public void writeObject(String path, VersionTree vt) {
        Output output = null;
        try {
            File saveFile = new File(path);
            if(!saveFile.getParentFile().exists()){
                saveFile.getParentFile().mkdirs();
            }
            output = new Output(new FileOutputStream(path));
            kryo.writeObject(output, vt);
        } catch (FileNotFoundException e) {
            throw new RuntimeException("版本树保存路径不存在:",e);
        }finally {
            IOUtils.closeQuietly(output);
        }
    }

    public VersionTree readObject(String path) {
        Input input = null;
        try {
            input = new Input(new FileInputStream(path));
            return kryo.readObject(input, VersionTree.class);
        } catch (FileNotFoundException e) {
            throw new RuntimeException("版本树读取路径不存在:",e);
        }finally {
            IOUtils.closeQuietly(input);
        }
    }

}
